<template>
	<div class="prescription-management">
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span>我的处方管理</span>
			</div>

			<!-- 处方列表 -->
			<el-table :data="myPrescriptionList" style="width: 100%" v-loading="loading">
				<!-- 基本信息列 -->
				<el-table-column prop="orderId" label="处方ID" width="80"></el-table-column>
				<el-table-column prop="visitId" label="诊疗号" width="120"></el-table-column>
				<el-table-column prop="orderType" label="类型" width="80">
					<template slot-scope="scope">
						<el-tag :type="scope.row.orderType === 'drug' ? 'success' : 'primary'" size="small">
							{{ scope.row.orderType === 'drug' ? '药品' : '检查' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="orderContent" label="内容" min-width="180">
					<template slot-scope="scope">
						<div v-if="scope.row.orderType === 'drug'">
							{{ scope.row.orderContent }}
							<div style="font-size: 12px; color: #909399;">
								规格：{{ scope.row.drugSpec }} | 用量：{{ scope.row.dosage }}{{ scope.row.dosageUnit }}
							</div>
						</div>
						<div v-else>
							{{ scope.row.orderContent }}
						</div>
					</template>
				</el-table-column>

				<!-- 可修改的字段 -->
				<el-table-column prop="frequency" label="频率/紧急程度" width="120">
					<template slot-scope="scope">
						<div v-if="scope.row.orderType === 'drug'">
							{{ scope.row.frequency }}
						</div>
						<div v-else>
							<el-tag :type="getEmergencyType(scope.row.frequency)" size="small">
								{{ scope.row.frequency }}
							</el-tag>
						</div>
					</template>
				</el-table-column>

				<el-table-column prop="startTime" label="开始时间">
					<template slot-scope="scope">
						{{ formatDateTime(scope.row.startTime) }}
					</template>
				</el-table-column>

				<el-table-column prop="endTime" label="结束时间" >
					<template slot-scope="scope">
						{{ formatDateTime(scope.row.endTime) }}
					</template>
				</el-table-column>

				<el-table-column prop="orderStatus" label="状态">
					<template slot-scope="scope">
						<el-tag :type="getStatusType(scope.row.orderStatus)" size="small">
							{{ getStatusText(scope.row.orderStatus) }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column prop="createdTime" label="创建时间" >
					<template slot-scope="scope">
						{{ formatDateTime(scope.row.createdTime) }}
					</template>
				</el-table-column>

				<!-- 操作列 -->
				<el-table-column label="操作" fixed="right">
					<template slot-scope="scope">
						<!-- 修改按钮 -->
						<el-button type="primary" size="mini" @click="handleEdit(scope.row)"
							:disabled="scope.row.orderStatus === 'completed' || scope.row.orderStatus === 'verified'">
							修改
						</el-button>

						<!-- 删除按钮 -->
						<el-button type="danger" size="mini" @click="handleDelete(scope.row)"
							:disabled="scope.row.orderStatus === 'completed'">
							删除
						</el-button>

						<!-- 审核按钮（只对pending状态的处方显示） -->
						<el-button v-if="scope.row.orderStatus === 'pending'" type="success" size="mini"
							@click="handleVerify(scope.row)">
							审核通过
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!-- 修改处方对话框 -->
		<el-dialog title="修改处方" :visible.sync="editDialogVisible" width="600px" @close="handleEditDialogClose">
			<el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
				<!-- 只读信息 -->
				<el-form-item label="处方ID">
					<el-input :value="editForm.orderId" readonly />
				</el-form-item>

				<el-form-item label="处方类型">
					<el-input :value="editForm.orderType === 'drug' ? '药品处方' : '检查处方'" readonly />
				</el-form-item>

				<el-form-item label="处方内容">
					<el-input :value="editForm.orderContent" readonly />
				</el-form-item>

				<!-- 药品处方额外信息 -->
				<template v-if="editForm.orderType === 'drug'">
					<el-form-item label="药品规格">
						<el-input :value="editForm.drugSpec" readonly />
					</el-form-item>

					<el-form-item label="用法用量">
						<el-input :value="`${editForm.dosage}${editForm.dosageUnit}`" readonly />
					</el-form-item>

					<el-form-item label="给药途径">
						<el-input :value="editForm.administrationRoute" readonly />
					</el-form-item>
				</template>
				<!-- 频率/紧急程度 -->
				<el-form-item :label="editForm.orderType === 'drug' ? '使用频次' : '紧急程度'" prop="frequency">
					<el-select v-model="editForm.frequency"
						:placeholder="`请选择${editForm.orderType === 'drug' ? '使用频次' : '紧急程度'}`" style="width: 100%">
						<el-option v-if="editForm.orderType === 'drug'" v-for="freq in drugFrequencies" :key="freq"
							:label="freq" :value="freq" />
						<el-option v-else v-for="emergency in emergencies" :key="emergency" :label="emergency"
							:value="emergency" />
					</el-select>
				</el-form-item>

				<!-- 开始时间 -->
				<el-form-item label="开始时间" prop="startTime">
					<el-date-picker v-model="editForm.startTime" type="datetime" placeholder="选择开始时间"
						value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
				</el-form-item>

				<!-- 结束时间（检查处方不需要） -->
				<el-form-item v-if="editForm.orderType === 'drug'" label="结束时间" prop="endTime">
					<el-date-picker v-model="editForm.endTime" type="datetime" placeholder="选择结束时间"
						value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
				</el-form-item>

				<!-- 状态 -->
				<el-form-item label="处方状态" prop="orderStatus">
					<el-select v-model="editForm.orderStatus" placeholder="请选择状态" style="width: 100%">
						<el-option label="待审核" value="pending" />
						<el-option label="已审核" value="verified" />
						<el-option label="已完成" value="completed" />
						<el-option label="已取消" value="cancelled" />
					</el-select>
				</el-form-item>
			</el-form>

			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitEdit" :loading="editing">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import http from '../../utils/request.js'

	export default {
		data() {
			return {
				loading: false,
				editing: false,
				myPrescriptionList: [],
				editDialogVisible: false,
				editForm: {
					orderId: '',
					orderType: '',
					orderContent: '',
					drugSpec: '',
					dosage: '',
					dosageUnit: '',
					administrationRoute: '',
					frequency: '',
					startTime: '',
					endTime: '',
					orderStatus: ''
				},
				editRules: {
					frequency: [{
						required: true,
						message: '请选择频率/紧急程度',
						trigger: 'change'
					}],
					startTime: [{
						required: true,
						message: '请选择开始时间',
						trigger: 'change'
					}],
					orderStatus: [{
						required: true,
						message: '请选择状态',
						trigger: 'change'
					}]
				},
				drugFrequencies: [
					'每日一次', '每日两次', '每日三次', '每日四次',
					'每6小时一次', '每8小时一次', '每12小时一次',
					'睡前服用', '必要时服用'
				],
				emergencies: ['立即', '紧急', '常规']
			}
		},
		async created() {
			await this.getMyPrescriptionList();
		},
		methods: {
			async getMyPrescriptionList() {
				this.loading = true;
				try {
					const resp = await http.get('/doctor/getMyPrescriptionList', {
						headers: {
							doctorId: this.$store.state.user.id
						}
					});
					this.myPrescriptionList = resp.data.data || [];
				} catch (error) {
					console.error('获取处方列表失败:', error);
					this.$message.error('获取处方列表失败');
				} finally {
					this.loading = false;
				}
			},

			// 格式化时间显示
			formatDateTime(dateTime) {
				if (!dateTime) return '-';
				return dateTime.replace('T', ' ').substring(0, 16);
			},

			// 获取状态标签类型
			getStatusType(status) {
				const statusMap = {
					'pending': 'warning',
					'verified': 'success',
					'completed': 'info',
					'cancelled': 'danger'
				};
				return statusMap[status] || 'info';
			},

			// 获取状态文本
			getStatusText(status) {
				const statusTextMap = {
					'pending': '待审核',
					'verified': '已审核',
					'completed': '已完成',
					'cancelled': '已取消'
				};
				return statusTextMap[status] || status;
			},

			// 获取紧急程度标签类型
			getEmergencyType(emergency) {
				const emergencyMap = {
					'立即': 'danger',
					'紧急': 'warning',
					'常规': 'info'
				};
				return emergencyMap[emergency] || 'info';
			},

			// 修改处方
			handleEdit(row) {
				this.editForm = {
					orderId: row.orderId,
					orderType: row.orderType,
					orderContent: row.orderContent,
					drugSpec: row.drugSpec,
					dosage: row.dosage,
					dosageUnit: row.dosageUnit,
					administrationRoute: row.administrationRoute,
					frequency: row.frequency,
					startTime: row.startTime,
					endTime: row.endTime || '',
					orderStatus: row.orderStatus
				};
				this.editDialogVisible = true;
			},

			// 删除处方
			async handleDelete(row) {
				try {
					await this.$confirm('确定要删除这条处方吗？', '提示', {
						type: 'warning'
					});

					const resp = await http.post('/doctor/deletePrescription', {
						orderId: row.orderId
					});

					if (resp.data.code === 1) {
						this.$message.success('删除成功');
						await this.getMyPrescriptionList(); // 刷新列表
					} else {
						this.$message.error(resp.data.msg || '删除失败');
					}
				} catch (error) {
					if (error !== 'cancel') {
						console.error('删除处方失败:', error);
						this.$message.error('删除失败');
					}
				}
			},

			// 审核通过
			async handleVerify(row) {
				try {
					await this.$confirm('确定要审核通过这条处方吗？', '提示', {
						type: 'warning'
					});

					const formData = {
						orderId: row.orderId,
						orderStatus: 'verified'
					};

					const resp = await http.post('/doctor/updatePrescription', formData);

					if (resp.data.code === 1) {
						this.$message.success('审核通过');
						await this.getMyPrescriptionList(); // 刷新列表
					} else {
						this.$message.error(resp.data.msg || '审核失败');
					}
				} catch (error) {
					if (error !== 'cancel') {
						console.error('审核处方失败:', error);
						this.$message.error('审核失败');
					}
				}
			},

			// 提交修改
			async submitEdit() {
				try {
					await this.$refs.editFormRef.validate();

					this.editing = true;

					// 构建更新数据，只包含可修改的字段
					const updateData = {
						orderId: this.editForm.orderId,
						frequency: this.editForm.frequency,
						startTime: this.editForm.startTime,
						orderStatus: this.editForm.orderStatus
					};

					// 药品处方需要更新endTime
					if (this.editForm.orderType === 'drug') {
						updateData.endTime = this.editForm.endTime;
					}

					const resp = await http.post('/doctor/updatePrescription', updateData);

					if (resp.data.code === 1) {
						this.$message.success('修改成功');
						this.editDialogVisible = false;
						await this.getMyPrescriptionList(); // 刷新列表
					} else {
						this.$message.error(resp.data.msg || '修改失败');
					}
				} catch (error) {
					if (error !== 'cancel') {
						console.error('修改处方失败:', error);
					}
				} finally {
					this.editing = false;
				}
			},

			// 关闭修改对话框
			handleEditDialogClose() {
				this.$refs.editFormRef.resetFields();
			}
		}
	}
</script>

<style scoped>
	.prescription-management {
		padding: 20px;
	}

	.box-card {
		margin-bottom: 20px;
	}

	.clearfix:before,
	.clearfix:after {
		display: table;
		content: "";
	}

	.clearfix:after {
		clear: both;
	}

	.el-table {
		margin-top: 20px;
	}
</style>